package utils;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import utils.getcode.GetToken;

import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import dbtools.WeiboDb;

public class CrawleFrFo implements Runnable {

	//public static final Log log =  LogFactory.getLog(CrawleFrFo.class);
	private static final Logger log = Logger.getLogger(CrawleFrFo.class);  

	
	WeiboDb db;
	GetFollowers gfo;
	GetFriends gfr;
	
	Weibo weibo;
	AccessToken at;
	
	public CrawleFrFo(){
		db = new WeiboDb();
		init();
	}
	
	private void init(){ // 初始化weibo和AccessToken
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
		try {
			weibo = new Weibo();
			
			GetToken gt = new GetToken(); 
			at = gt.getAccessToken();
			
		} catch (Exception e) {
			log.debug(e);
		}
	}
	
	@Override
	public void run() {
		int start = 1;
		StartPoint sp = new StartPoint();
		try {
			String weiboId_Start = sp.get("weiboId_Start_page");
			if (!(weiboId_Start == null || "".equals(weiboId_Start))){
				start = Integer.parseInt(weiboId_Start);
			}else{
				sp.save("weiboId_Start_page", String.valueOf(start));
			}
			
			while (true) {
				List<String> ids = db.getWeiboId(start);

				if (ids == null || ids.size() == 0) {
					Thread.currentThread().sleep(1000 * 60 * 10); // wait for 10
																	// min
				}else{
					for(Iterator<String> i = ids.iterator(); i.hasNext();){
						start++;
						String weiboId = i.next();
						this.gfo = new GetFollowers(weibo,at,weiboId);
						this.gfr = new GetFriends(weibo,at,weiboId);
						Thread threadGfo = new Thread(gfo);
						Thread threadGfr = new Thread(gfr);
						threadGfo.start();
						threadGfr.start();
					}
					Thread.currentThread().sleep(1000 * 60 * 2); // wait for 2 min
				}
				sp.save("weiboId_Start_page", String.valueOf(start));
			}
			
		} catch (Exception e) {
			log.debug(e);
		}
	}
	
	
}
